'use strict';

const fs = require('fs');
const router = require('koa-router')()


function getRouteFile(filePath) {
    let tmpPath = __dirname || filePath;
    let files = fs.readdirSync(tmpPath);
    let routeFiles = files.filter(item => {
        return item.endsWith('.js') && item !== 'index.js';
    });

    return routeFiles;
}

function registeRouteFile(router, routeFiles) {
    routeFiles.forEach(item => {
        let routePath = __dirname + '/' + item;
        let obj = require(routePath);
        for (let key in obj) {
            let tmp = key.split(' ');
            let routeMethod = tmp[0]
            let routeUrl = tmp[1]
            let routeFunc = obj[key]

            if (routeMethod === 'post') {
                router.post(routeUrl, routeFunc)
            } else if (routeMethod === 'get') {
                router.get(routeUrl, routeFunc)
            } else if (routeMethod === 'put') {
                router.put(routeUrl, routeFunc)
            } else if (routeMethod === 'delete') {
                router.delete(routeUrl, routeFunc)
            } else {

            }
        }
    });
    return router.routes();
}

module.exports = function(){
    let routeFiles = getRouteFile();
    let fn = registeRouteFile(router,routeFiles)
    return fn
}